import type { MenuNodeType } from '../enums'
import type { IMenu } from './menu'
import { Tree } from '@pkgs/utils'
import { defineStore } from 'pinia'
import useMenuStore from './menu'

export interface IApp {
  type: MenuNodeType
  name: string
  code: string
  projectCode: string
  url: string
  active: boolean
  sort: number
  children: IMenu[]
}

interface IState {
  appCode: string
  activeApp: IApp | null
  apps: IApp[]
}

export const useAppStore = defineStore('app-store', {
  state: (): IState => ({
    appCode: '',
    activeApp: null,
    apps: [],
  }),

  getters: {
    getAppCode: state => state.appCode,

    getAppName: state => state.activeApp?.name ?? '',

    getApps: state => state.apps,
  },

  actions: {
    getMenus(appCode: string) {
      const menus = this.apps.find(app => app.code === appCode)?.children ?? []
      new Tree<IMenu>().traversal(menus, (menu) => {
        menu.appCode = appCode
      })
      return menus
    },

    setAppCode(code: string): IMenu[] {
      this.appCode = code

      const activeApp = this.apps.find((app: IApp) => app.code === this.appCode)
      if (activeApp) {
        this.activeApp = activeApp
      }

      const menus = this.getMenus(this.appCode)

      const menuStore = useMenuStore()
      menuStore.setMenus(menus)

      return menus
    },

    setApps(list: IApp[], appCode?: string) {
      this.apps = list

      if (appCode) {
        this.setAppCode(appCode)
      }
      else {
        const activeApp = this.apps.find((app: IApp) => app.active)
        if (activeApp) {
          this.setAppCode(activeApp.code)
        }
      }
    },

    updateApps(list: IApp[]) {
      this.apps = list
    },
  },

  persist: true,
})

export default useAppStore
